﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using FanaticRock.Core.Interfaces;
using FanaticRock.Interfaces;

namespace FanaticRock.Helpers
{
    public static class ObservableCollectionHelper
    {
        internal static object _lockObj  = new object();
        ///<summary>从 Model 变为 IFromModel 对象的集合。</summary>
        public static ObservableCollection<TFromModel> CreateFromModel<TModel, TFromModel>(IEnumerable<TModel> source)
            where TFromModel : IFromModel<TModel>, new()
        {
            var collection = new ObservableCollection<TFromModel>();

            if (source == null) return collection;

            foreach (var item in source)
            {
                var fromModel = new TFromModel();
                fromModel.Load(item);
                collection.Add(fromModel);
            }

            return collection;
        }

        ///<summary>从 IFromModel 的集合变为 Model 的数组。</summary>
        public static TModel[] ExportFromModel<TModel, TFromModel>(ObservableCollection<TFromModel> collection)
               where TFromModel : IFromModel<TModel>
        {
            if (collection == null) return null;
            return collection.Select(i => i.Export()).ToArray();
        }

        ///<summary>更新下标。</summary>
        public static void UpdateIndex<T>(ObservableCollection<T> collection)where T: IHasIndex
        {
            BindingOperations.EnableCollectionSynchronization(collection, _lockObj);
            if (collection == null) return;
            for (var i = 0; i < collection.Count; i++)
            {
                collection[i].IndexInCollection = i+1;
            }
            BindingOperations.DisableCollectionSynchronization(collection);
        }

        public static ObservableCollection<T> Clone<T>(ObservableCollection<T> collection)
        {
            if (collection == null) return new ObservableCollection<T>();
            return new ObservableCollection<T>(collection);
        }

    }
}
